package com.pocketsweet.ui;

import java.util.ArrayList;
import java.util.Timer;

import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.avos.avoscloud.AVFile;
import com.easemob.util.HanziToPinyin;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLCache;
import com.pocketsweet.MLContext;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.chatui.Constant;
import com.pocketsweet.chatui.domain.User;
import com.pocketsweet.model.MLVoice;
import com.pocketsweet.service.UpdateService;
import com.pocketsweet.service.UserService;
import com.pocketsweet.service.shareService;
import com.pocketsweet.ui.fragments.TempHomeFragment;
import com.pocketsweet.ui.uilib.FragmentTabHost;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.MyOnTouchListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.umeng.update.UpdateConfig;

public class TempMain extends BaseActivity implements OnClickListener {

    public boolean msgFragmentisShow = false;
    public boolean friendFragmentisShow = false;
    public boolean selfFragmentisShow = false;

    /*
     * 其他页面信息
     */
    private static TempMain _instance;
    private shareService myShareSevice;// 友盟分享service
    private Fragment mContent;
    private long mExitTime = 0;// 退出事件用到的事件
    public static final String ACTION_CHOOSE_CHANGE = "action_choose_change";

    public FragmentTransaction mFragmentTransaction;
    public FragmentManager fragmentManager;
    public int currentTabIndex = 0;
    private int index;
    private Button[] mTabs;
    // 定义FragmentTabHost对象
    private FragmentTabHost mTabHost;

    // 定义一个布局
    private LayoutInflater layoutInflater;

    private TempHomeFragment mHomeFragment;
    // private TempHomeFragment mChatAllHistoryFragment;
    // private TempHomeFragment mExploreFragment;
    // private TempHomeFragment mSelfFragment;
    private Fragment[] fragments;

    // 腾讯定位
    private static final long[] INTERVALS = new long[]{2 * 1000, 3 * 1000,
            5 * 1000, 10 * 1000};
    private static final int DEFAULT = 2;
    private int mIndex = DEFAULT;
    private long mInterval = INTERVALS[DEFAULT];
    private TencentLocationManager mLocationManager;
    public static String locatedCity;
    // 声线
    public static AVFile audioFile;
    public static String curPlayId = "";// 当前播放的id
    public static String playId = "";// 要播放的Id
    public static int playItem;// 要播放的Id
    public static int curPlayItem;// 当前播放地item
    public static MediaPlayer mMediaPlayer;
    public static Timer MediaTimer;
    public static ArrayList<MLVoice> voiceList = new ArrayList<MLVoice>();
    // 自动更新监测
    private UpdateService myUpdateService;
    private HeaderLayout rvHeader;

    public static int choosedSex = 0;// 0为全部；1为男；2为女
    public static int choosedCity = 0;// 0为全部；1为同城
    public static int choosedType = 0;// 0为全部：1为只查看推荐的
    public static boolean needRefresh = false;// 告知列表页面是否需要刷新
    public static final int REQUEST_CODE_CHOOSE = 0x01;

    public static TempMain getInstance() {
        return _instance;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        _instance = this;
        MLContext.deleteAll(); // 删除所有sharepreference
        // overridePendingTransition(R.anim.fade_in, R.anim.unzoom_out);
        if (savedInstanceState != null
                && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED,
                false)) {
            // 防止被移除后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
            // 三个fragment里加的判断同理
            MLApplication.getInstance().logout(null);
            finish();
            startActivity(new Intent(this, TempMain.class));
            return;
        } else if (savedInstanceState != null
                && savedInstanceState.getBoolean("isConflict", false)) {
            // 防止被T后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
            // 三个fragment里加的判断同理
            finish();
            startActivity(new Intent(this, TempMain.class));
            return;
        }
        MLApplication.getInstance().isLogin = false;
        setContentView(R.layout.activity_main);
        // if (UserService.getCurrentUser() == null) {
        // startActivity(new Intent(this, Login.class));
        // }
        // setLocalImage();
        // 初始化一些组件，包括欢迎页面，版本更新检查和社会化分享，高德定位
        initComponents();
        initView();

    }

    private void setLocalImage() {
        if (UserService.getCurrentUser() == null) {
            return;
        }
        // 兼容第一版本，如果是更新上来的，添加
        if (MLCache.getCache().getAsJSONObject(UserService.getCurrentUserId()) == null) {
            MLCache.init(MLApplication.getContext());
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    private void initView() {

        mHomeFragment = new TempHomeFragment();
        fragments = new Fragment[]{mHomeFragment};
        // 添加显示第一个fragment
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
        ft.add(R.id.fragment_container, mHomeFragment).show(mHomeFragment)
                .commitAllowingStateLoss();

        mTabs = new Button[4];
        mTabs[0] = (Button) findViewById(R.id.btnHome);
        mTabs[1] = (Button) findViewById(R.id.btnConversation);
        mTabs[2] = (Button) findViewById(R.id.btnFriend);
        mTabs[3] = (Button) findViewById(R.id.btnSelf);
        // 把第一个tab设为选中状态
        mTabs[0].setSelected(true);
        // 导航header
        rvHeader = (HeaderLayout) findViewById(R.id.mainHeader);
        rvHeader.init(HeaderStyle.TEXT_TITLE_IMG);
        rvHeader.Initcursor();
        rvHeader.setTvNewOnline("空闲恋人 ");
        rvHeader.setTvRecomend(" 梦想恋人");
        rvHeader.setLeftContentShow(View.INVISIBLE);
        mMediaPlayer = new MediaPlayer(); // 初始化声线
        mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                if (MediaTimer != null) {
                    MediaTimer.cancel();
                }
            }
        });
    }

    /**
     * button点击事件
     *
     * @param view
     */
    public void onTabClicked(View view) {
        if (view.getId() != R.id.btnHome) {

        }
        switch (view.getId()) {
            case R.id.btnHome:
                break;
            case R.id.btnConversation:
                Intent intentConversation = new Intent(this, Login.class);
                startActivity(intentConversation);
                this.finish();
                break;
            case R.id.btnFriend:
                Intent intentFriend = new Intent(this, Login.class);
                startActivity(intentFriend);
                this.finish();
                break;
            case R.id.btnSelf:
                Intent intentSelf = new Intent(this, Login.class);
                startActivity(intentSelf);
                this.finish();
                break;
        }
        // if (currentTabIndex != index) {
        // FragmentTransaction trx = getSupportFragmentManager()
        // .beginTransaction();
        // if (index == 1 && msgFragmentisShow == false) {
        // trx.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
        // msgFragmentisShow = true;
        // }
        // if (index == 2 && friendFragmentisShow == false) {
        // trx.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
        // friendFragmentisShow = true;
        // }
        // if (index == 3 && selfFragmentisShow == false) {
        // trx.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
        // selfFragmentisShow = true;
        // }
        // trx.hide(fragments[currentTabIndex]);
        // if (!fragments[index].isAdded()) {
        // trx.add(R.id.fragment_container, fragments[index]);
        // }
        // trx.show(fragments[index]).commit();
        // }
        // mTabs[currentTabIndex].setSelected(false);
        // // 把当前tab设为选中状态
        // mTabs[index].setSelected(true);
        // currentTabIndex = index;
    }

    private void initComponents() {
        // 检查新版本
        myUpdateService = new UpdateService(TempMain.this, true);
        myUpdateService.update();
        UpdateConfig.setUpdateAutoPopup(false);

        // 社会化分享
        myShareSevice = new shareService(this);

        // 高德定位
        startLocation();
    }

    private void startLocation() {
        mLocationManager = TencentLocationManager.getInstance(TempMain.this);
        // 创建定位请求
        TencentLocationRequest request = TencentLocationRequest
                .create()
                .setRequestLevel(
                        TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA)
                .setInterval(mInterval); // 设置定位周期, 建议值为 1s-20s
    }

    /**
     * 重写onKeyDown方法
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showExitAlet();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showExitAlet() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast toast = Toast.makeText(TempMain.this, "再按一次退出程序",
                    Toast.LENGTH_LONG);
            // 可以控制toast显示的位置
            toast.setGravity(Gravity.BOTTOM, 0, 150);
            toast.show();
            mExitTime = System.currentTimeMillis();

        } else {
            TempMain.this.finish();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        for (MyOnTouchListener listener : touchListeners) {
            listener.onTouchEvent(event);
        }
        return super.onTouchEvent(event);
    }

    private ArrayList<MyOnTouchListener> touchListeners = new ArrayList<MyOnTouchListener>();

    public void registerListener(MyOnTouchListener listener) {
        touchListeners.add(listener);
    }

    public void unRegisterListener(MyOnTouchListener listener) {
        touchListeners.remove(listener);
    }

    public HeaderLayout getHeader() {
        return rvHeader;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Fragment selfFragment = fragments[currentTabIndex];
        selfFragment.onActivityResult(requestCode, resultCode, data);

    }

    // /**
    // * 刷新编辑推荐消息数
    // */
    // public void updateUnreadRecommendLable() {
    // runOnUiThread(new Runnable() {
    // public void run() {
    // int count = getUnreadRecommendCountTotal();
    // Log.e("getUnreadRecommendCountTotal", count + "");
    // if (count > 0) {
    // unread_recommend.setVisibility(View.VISIBLE);
    // } else {
    // unread_recommend.setVisibility(View.INVISIBLE);
    // }
    // }
    // });
    //
    // }

    /**
     * set head
     *
     * @param username
     * @return
     */
    User setUserHead(String username) {
        User user = new User();
        user.setUsername(username);
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(HanziToPinyin.getInstance()
                    .get(headerName.substring(0, 1)).get(0).target.substring(0,
                            1).toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
        return user;
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        }
    }
}
